﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using Cms.Web.Framework.Plugins.Attributes;
using iLib.Web.UI.WebControls;
using Content = Cms.Domain.Content;
using Page = Cms.Domain.Page;
using SortDirection = Cms.Domain.SortDirection;

namespace Cms.Web.Framework.Plugins
{
    public class ListPages : BaseTemplatedPlugin
    {
        // Property fields
        private int _categoryID;
        private string _publishedDateFormat;

        // Template controls
        private iRepeater rpPages;
        private LocalizedPluginLiteral lplReadMore;

        [Enumeration("Categories", true)]
        public int CategoryID
        {
            get { return _categoryID; }
            set { _categoryID = value; }
        }

        [Enumeration("ContentSortMode", true)]
        public ContentSortMode SortMode { get; set; }

        [Enumeration("SortDirections", true)]
        public SortDirection SortDirection { get; set; }

        public int SkipFirstCount { get; set; }

        public int ReturnCount { get; set; }

        public string PublishedDateFormat
        {
            get { return _publishedDateFormat; }
            set { _publishedDateFormat = value; }
        }
        
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                rpPages = (iRepeater)FindControl("rpPages");
                lplReadMore = (LocalizedPluginLiteral)FindControl("lplReadMore");
                rpPages.ItemDataBound += rpPages_ItemDataBound;
                IList<Domain.Page> pages = GetPages();
                rpPages.SelectedIndex = -1;
                if (RequestDetails.Page != null)
                {
                    for (int i = 0; i < pages.Count; i++)
                    {
                        if (pages[i].ID == RequestDetails.Page.ID)
                        {
                            rpPages.SelectedIndex = i;
                        }
                    }
                }
                rpPages.DataSource = pages;
                rpPages.DataBind();
            }
            catch (Exception ex)
            {
                Logging.LogError("ListPages", ex);
                Controls.Clear();
            }
        }

        protected IList<Page> GetPages()
        {
            IPageRepository pageRepository = new PageRepository();
            Category category = pageRepository.GetCategory(_categoryID);
            IList<Page> pages = category.Pages.Where(p => p.IsPublishedNow()).ToList();
            foreach (Folder folder in category.Folders)
            {
                foreach (Page p in
                    folder.GetAllPagesInThisFolderAndBelow()
                        .Where(p => !pages.Contains(p) && p.IsPublishedNow() && p.GetPublishedTimestamp(RequestDetails.Locale.ID).HasValue))
                {
                    pages.Add(p);
                }
            }
            return pages;
        }

        protected void rpPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem && e.Item.ItemType != ListItemType.SelectedItem)
            {
                return;
            }
            var page = (Cms.Domain.Page)e.Item.DataItem;
            var litTitle = (Literal)e.Item.FindControl("litTitle");
            var litDescription = (Literal)e.Item.FindControl("litDescription");
            var litPublishedBy = (Literal)e.Item.FindControl("litPublishedBy");
            var litPublishedDate = (Literal)e.Item.FindControl("litPublishedDate");
            var hlReadMore = (HyperLink)e.Item.FindControl("hlReadMore");
            if (hlReadMore != null)
            {
                hlReadMore.NavigateUrl = "~/";
                if (RequestDetails.Locale != RequestDetails.Site.DefaultLocale)
                {
                    hlReadMore.NavigateUrl += RequestDetails.Locale.UrlCode + "/";
                }
                hlReadMore.NavigateUrl += page.GetVirtualPath();
                if (lplReadMore != null)
                {
                    hlReadMore.Text = lplReadMore.Text;
                }
            }
            if (litDescription != null)
            {
                litDescription.Text = page.LocalizedProperties[RequestDetails.Locale.ID].ListingsDescription;
            }
            if (litTitle != null)
            {
                if (page.LocalizedProperties.ContainsKey(RequestDetails.Locale.ID))
                {
                    litTitle.Text = page.LocalizedProperties[RequestDetails.Locale.ID].ListingsTitle;
                }
            }
            if (litPublishedBy != null)
            {
                litPublishedBy.Text = page.GetPublishedBy(RequestDetails.Locale.ID);
            }
            if (litPublishedDate != null)
            {
                DateTime? publishedDate = page.GetPublishedTimestamp(RequestDetails.Locale.ID);
                if (!publishedDate.HasValue)
                {
                    return;
                }
                litPublishedDate.Text = !string.IsNullOrEmpty(_publishedDateFormat)
                                            ? publishedDate.Value.ToString(_publishedDateFormat)
                                            : publishedDate.Value.ToString();
            }
        }
    }
}